package com.yy.hi.library.restful

import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.ConcurrentHashMap

open class HiRestful(val baseUrl: String, val callFactory: HiCall.Factory) {
    private var interceptors: MutableList<HiInterceptor> = mutableListOf()
    private var methodService: ConcurrentHashMap<Method, MethodParse> = ConcurrentHashMap()
    private val scheduler: Scheduler

    init {
        scheduler = Scheduler(callFactory, interceptors)
    }

    fun addInterceptor(interceptor: HiInterceptor) {
        interceptors.add(interceptor)
    }

    fun <T> create(service: Class<T>): T {
        return Proxy.newProxyInstance(service.classLoader,
            arrayOf<Class<*>>(service)) { proxy, method, args ->
            var methodParse = methodService.get(method)
            if (methodParse == null) {
                methodParse = MethodParse.parse(baseUrl, method, args)
                methodService.put(method, methodParse)
            }
            val request = methodParse.newRequest()
//            callFactory.newCall(request)
            scheduler.newCall(request)
        } as T
    }
}